﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Estados;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Modulos
{
	public partial class ModulosViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Estado> _estadosModulo;

		/// <summary>
		/// 
		/// </summary>
		private Estado _estadoModulo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Estado> EstadosModulo
		{
			get
			{
				return _estadosModulo;
			}
			private set
			{
				_estadosModulo = value;
				if (_estadosModulo != null)
					RaisePropertyChanged("EstadosModulo");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Estado EstadoModulo
		{
			get
			{
				return _estadoModulo;
			}
			private set
			{
				_estadoModulo = value;
				if (_estadoModulo != null)
					RaisePropertyChanged("EstadoModulo");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadEstadosModulo()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IEstadoService service = IoCFactory.Resolve<IEstadoService>();
					e.Result = service.FindAllEstados();
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						EstadosModulo = e.Result as List<Estado>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentEstadoModulo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				EstadoModulo = bindingSource.Current as Estado;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnEstadosModuloPropertyChanged()
		{
			_view.estadosModuloBindingSource.DataSource = EstadosModulo;
			_view.estadosModuloBindingSource.CurrentChanged += SetCurrentEstadoModulo;
			SetCurrentEstadoModulo(_view.estadosModuloBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnEstadoModuloPropertyChanged()
		{
			LoadDistritosModulo();
			LoadMunicipiosModulo();
			LoadJuntasModulo();
		}

		#endregion

	}
}